import aiohttp

class BitAPI:
    def __init__(self, host='127.0.0.1', port=54345):
        self.url = f"http://{host}:{port}"
        self.headers = {'Content-Type': 'application/json'}

    async def createBrowser(self, host='', port='', noproxy='noproxy'):
        json_data = {
            'name': 'google',
            'remark': '',
            'proxyMethod': 2,
            'proxyType': 'noproxy',
            'host': '',
            'port': '',
            'proxyUserName': '',
            'abortImage': False,
            'clearCacheFilesBeforeLaunch': True,
            'randomFingerprint': True,
            "browserFingerPrint": {
                # 'coreVersion': '124',
                # 'ostype': 'PC',
                # 'os': 'MacIntel',
                'isIpCreateLanguage': False,
                'languages': 'en-SG',
                # 'version': '125'
                'openWidth': 800,
                'openHeight': 500,
            }
        }

        async with aiohttp.ClientSession() as session:
            async with session.post(f"{self.url}/browser/update", json=json_data, headers=self.headers) as resp:
                res = await resp.json()
                if res['success']:
                    browserId = res['data']['id']
                    print(browserId)
                    return browserId
                else:
                    return None

    async def openBrowser(self, browserId, config=None):
        json_data = {"id": browserId}

        if config and isinstance(config, dict):
            json_data.update(config)

        async with aiohttp.ClientSession() as session:
            async with session.post(f"{self.url}/browser/open", json=json_data, headers=self.headers) as resp:
                res = await resp.json()
                return res

    async def closeBrowser(self, browserId):
        json_data = {'id': f'{browserId}'}
        async with aiohttp.ClientSession() as session:
            await session.post(f"{self.url}/browser/close", json=json_data, headers=self.headers)

    async def detailBrowser(self, browserId):
        json_data = {'id': f'{browserId}'}
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{self.url}/browser/detail", json=json_data, headers=self.headers) as resp:
                res = await resp.json()
                return res

    async def deleteBrowser(self, browserId):
        json_data = {'id': f'{browserId}'}
        async with aiohttp.ClientSession() as session:
            await session.post(f"{self.url}/browser/delete", json=json_data, headers=self.headers)

    async def updateBrowser(self, browserId):
        fingers = await self.fingerprint(browserId)
        browserFingerPrint = {
            # 'coreVersion': '124',
            'ostype': 'PC',
            # 'os': 'MacIntel',
            # 'isIpCreateLanguage': False,
            'languages': 'en-SG',
            # 'version': '125'
        }
        if fingers.get('success') == True:
            browserFingerPrint = fingers.get('data')

        json_data = {
            'ids': f'[{browserId}]',
            'browserFingerPrint': browserFingerPrint
        }
        async with aiohttp.ClientSession() as session:
            await session.post(f"{self.url}/browser/update/partial", json=json_data, headers=self.headers)

    async def clear_cookies(self, browserId):
        json_data = {'browserId': f'{browserId}', 'cookies': []}
        async with aiohttp.ClientSession() as session:
            await session.post(f"{self.url}/browser/cookies/set", json=json_data, headers=self.headers)

    async def fingerprint(self, browserId):
        json_data = {'browserId': f'{browserId}'}
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{self.url}/browser/fingerprint/random", json=json_data, headers=self.headers) as resp:
                res = await resp.json()
                return res